package com.ruoyi.merchant.shop.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.utils.HttpUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.merchant.shop.domain.LocationResult;
import com.ruoyi.merchant.shop.service.ILocationService;

/**
 * 地理位置服务实现类
 * 
 * @author zzr
 * @date 2025-09-14
 */
@Service
public class LocationServiceImpl implements ILocationService {
    
    private static final Logger log = LoggerFactory.getLogger(LocationServiceImpl.class);
    
    // 腾讯地图API配置
    private static final String TENCENT_MAP_API_HOST = "https://apis.map.qq.com";
    private static final String GEOCODING_PATH = "/ws/geocoder/v1/";
    private static final String REVERSE_GEOCODING_PATH = "/ws/geocoder/v1/";
    
    // 请替换为您的腾讯地图API密钥
    private static final String TENCENT_MAP_KEY = "XA5BZ-3JIKJ-LHXFX-XAHBN-M7HWV-64BMN";
    
    @Override
    public LocationResult getLocationByAddress(String address) {
        if (StringUtils.isEmpty(address)) {
            return new LocationResult(1, "地址不能为空");
        }
        
        try {
            // 构建请求参数
            Map<String, String> querys = new HashMap<>();
            querys.put("address", address);
            querys.put("key", TENCENT_MAP_KEY);
            
            // 发送HTTP请求
            String response = HttpUtils.doPost(TENCENT_MAP_API_HOST, GEOCODING_PATH, "GET", null, querys, null);
            
            log.info("腾讯地图API响应: {}", response);
            
            // 解析响应结果
            return parseGeocodingResponse(response);
            
        } catch (Exception e) {
            log.error("调用腾讯地图API获取坐标失败: {}", e.getMessage(), e);
            return new LocationResult(1, "获取坐标失败: " + e.getMessage());
        }
    }
    
    @Override
    public LocationResult getAddressByLocation(String longitude, String latitude) {
        if (StringUtils.isEmpty(longitude) || StringUtils.isEmpty(latitude)) {
            return new LocationResult(1, "经纬度不能为空");
        }
        
        try {
            // 构建请求参数
            Map<String, String> querys = new HashMap<>();
            querys.put("location", latitude + "," + longitude); // 注意：腾讯地图API格式是纬度,经度
            querys.put("key", TENCENT_MAP_KEY);
            
            // 发送HTTP请求
            String response = HttpUtils.doPost(TENCENT_MAP_API_HOST, REVERSE_GEOCODING_PATH, "GET", null, querys, null);
            
            log.info("腾讯地图逆地理编码API响应: {}", response);
            
            // 解析响应结果
            return parseReverseGeocodingResponse(response);
            
        } catch (Exception e) {
            log.error("调用腾讯地图逆地理编码API失败: {}", e.getMessage(), e);
            return new LocationResult(1, "获取地址失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析地理编码响应结果
     */
    private LocationResult parseGeocodingResponse(String response) {
        try {
            JSONObject jsonResponse = JSON.parseObject(response);
            Integer status = jsonResponse.getInteger("status");
            
            if (status != null && status == 0) {
                JSONObject result = jsonResponse.getJSONObject("result");
                if (result != null) {
                    JSONObject location = result.getJSONObject("location");
                    if (location != null) {
                        String longitude = location.getString("lng");
                        String latitude = location.getString("lat");
                        String address = result.getString("address");
                        
                        return new LocationResult(longitude, latitude, address);
                    }
                }
            }
            
            String message = jsonResponse.getString("message");
            return new LocationResult(status != null ? status : 1, message != null ? message : "解析响应失败");
            
        } catch (Exception e) {
            log.error("解析地理编码响应失败: {}", e.getMessage(), e);
            return new LocationResult(1, "解析响应失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析逆地理编码响应结果
     */
    private LocationResult parseReverseGeocodingResponse(String response) {
        try {
            JSONObject jsonResponse = JSON.parseObject(response);
            Integer status = jsonResponse.getInteger("status");
            
            if (status != null && status == 0) {
                JSONObject result = jsonResponse.getJSONObject("result");
                if (result != null) {
                    JSONObject addressComponent = result.getJSONObject("address_component");
                    if (addressComponent != null) {
                        String address = result.getString("address");
                        String longitude = result.getJSONObject("location").getString("lng");
                        String latitude = result.getJSONObject("location").getString("lat");
                        
                        return new LocationResult(longitude, latitude, address);
                    }
                }
            }
            
            String message = jsonResponse.getString("message");
            return new LocationResult(status != null ? status : 1, message != null ? message : "解析响应失败");
            
        } catch (Exception e) {
            log.error("解析逆地理编码响应失败: {}", e.getMessage(), e);
            return new LocationResult(1, "解析响应失败: " + e.getMessage());
        }
    }
}